package com.wuyou.sso.common.serializer;

import cn.hutool.core.util.StrUtil;
import com.wuyou.sso.common.component.CustomizedRedisTokenStore;
import com.wuyou.sso.common.component.KeyStrResolver;
import com.wuyou.sso.common.contant.AuthConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 令牌存储自动配置
 *
 * @author lishangbu
 * @date 2021/2/6
 */
@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class TokenStoreAutoConfiguration {

    private final KeyStrResolver tenantKeyStrResolver;

    private final RedisConnectionFactory redisConnectionFactory;

    @Bean
    public TokenStore tokenStore() {
        CustomizedRedisTokenStore tokenStore = new CustomizedRedisTokenStore(redisConnectionFactory, tenantKeyStrResolver);
        tokenStore.setPrefix(AuthConstants.PROJECT_PREFIX + AuthConstants.OAUTH_PREFIX);
        tokenStore.setAuthenticationKeyGenerator(new DefaultAuthenticationKeyGenerator() {
            @Override
            public String extractKey(OAuth2Authentication authentication) {
                // 增加租户隔离部分 租户ID:原生计算值
                return tenantKeyStrResolver.extract(super.extractKey(authentication), StrUtil.COLON);
            }
        });
        return tokenStore;
    }
}
